package cn.edu.scau.cmi.lishuoxin.interProgramming.experiment10.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import Hibernate.cn.edu.scau.cmi.lishuoxin.client.AlertBox;
import cn.edu.scau.cmi.lishuoxin.interProgramming.experiment10.domain.User;
import cn.edu.scau.cmi.lishuoxin.util.C3P0Utils;


public class UserDao {
	private AlertBox alert = new AlertBox();

	//添加用户
	public void insertUser(User user) {
		
		try {
			// 1.获取核心类queryRunner,只要给连接池就好了，自动获取连接
			QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
			// 2.编写SQL语句
			String sql = "insert into user values(?,?,?,?,?)";
			//3.设置参数
			Object[] params = {user.getId(),user.getUsername(),user.getBirthday(),user.getSex(),user.getAddress()};
			//4.执行sql语句
			int row = qr.update(sql, params);
			if(row>0) {
				alert.display("添加用户成功！");
				alert.display(user.toString());
			}else {
				alert.display("添加用户失败！");
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	//删除用户
	public void deleteUser(int id) {
		try {
			QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
			String sql = "delete from user where id = ?";
			int row = qr.update(sql, id);
			if(row>0) {
				alert.display("删除用户成功！");
			}else {
				alert.display("删除用户失败！");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	//查询用户
	public void selectUserById(int id) {
		try {
			QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
			String sql = "select * from user where id = ?";
			User user = qr.query(sql, id, new BeanHandler<User>(User.class));
			if(user!=null) {
				alert.display(user.toString());
			}else {
				alert.display("查询失败！");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	//修改用户
	public void updateUser(User user) {
		try {
			QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
			String sql = "update user set username=?,birthday=?,sex=?,address=? where id=?";
			Object[] params = {user.getUsername(),user.getBirthday(),user.getSex(),user.getAddress(),user.getId()};
			int row = qr.update(sql, params);
			if(row>0) {
				alert.display("修改用户成功！");
			}else {
				alert.display("修改用户失败！");
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}
